﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolCode.Services;
using CoolCode.OfficeToolkit.Excel;
using CoolCode.Entities;
using CoolCode.Caching;

namespace CoolCode.Web.UI.Views.Check
{
    public partial class ImportData : AuthPage
    {
        private IInspectionService _Service;
        public IInspectionService Service
        {
            get
            {
                if (_Service == null)
                {
                    _Service = ServiceFactory.Produce<IInspectionService>();
                }
                return _Service;
            }
        }

        private const int PageSize = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            handleEvents();

            lnkSave.Enabled = false;
            if (!IsPostBack)
            {
            }
        }

        protected void handleEvents()
        {
            // Products.PageIndexChanging += new GridViewPageEventHandler(Products_PageIndexChanging);
            lnkUpload.Click += new EventHandler(lnkUpload_Click);
            lnkSave.Click += new EventHandler(lnkSave_Click);
        }

        //protected void Products_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    BindData_Master(new PageParam(e.NewPageIndex, PageSize));
        //}

        //private void BindData_Master(PageParam p)
        //{
        //    //Guid guid = new Guid(hidGuid.Value);
        //    //var list = Service.PagingOutbound(guid, p);
        //    //Products.Model = list;
        //    //Products.DataBind();
        //}

        protected void lnkUpload_Click(object sender, EventArgs e)
        {
            Guid guid = Guid.NewGuid();
            string guidString = guid.ToString();
            hidGuid.Value = guid.ToString();
            string key = getCacheKey();
            int columnCount = 17;
            if (Request.Files.Count == 0)
            {
                udpHeader.Alert("找不到上传文件");
                return;
            }

            string savePath = Utility.GetMapPath("~/Output/" + guid + ".xls");
            try
            {
                Request.Files[0].SaveAs(savePath);
            }
            catch (Exception exp)
            {
                udpHeader.Alert("保存上传文件出错！错误信息：", exp);
                return;
            }
                List<Inspection> list = new List<Inspection>();
            try
            {
                using (ExcelHelper helper = new ExcelHelper(savePath))
                {
                    helper.Seek(3);
                    ExcelRow dataRow = null;
                    do
                    {
                        dataRow = helper.ReadLine();
                        if (dataRow != null && dataRow.CountNullOrEmpty() <= 4 && dataRow.Length >= columnCount)
                        {
                            try
                            {
                                Inspection model = new Inspection
                                {
                                    ProductID = dataRow.Read<string>((int)InspectionColumn.ProductID - 2),
                                    ProductSpec = dataRow.Read<string>((int)InspectionColumn.ProductSpec - 2),
                                    Checker = dataRow.Read<string>((int)InspectionColumn.Checker - 2),
                                    CheckDate = dataRow.Read<DateTime>((int)InspectionColumn.CheckDate - 2),
                                    Face = dataRow.Read<string>((int)InspectionColumn.Face - 2),
                                    Degumming = dataRow.Read<string>((int)InspectionColumn.Degumming - 2),
                                    Appearance = dataRow.Read<string>((int)InspectionColumn.Appearance - 2),
                                    Burse = dataRow.Read<string>((int)InspectionColumn.Burse - 2),
                                    Drawback = dataRow.Read<string>((int)InspectionColumn.Drawback - 2),
                                    ConeHeight = dataRow.Read<decimal>((int)InspectionColumn.ConeHeight - 2),
                                    SacculusLength = dataRow.Read<decimal>((int)InspectionColumn.SacculusLength - 2),
                                    SacculusStretch = dataRow.Read<decimal>((int)InspectionColumn.SacculusStretch - 2),
                                    Interlayer = dataRow.Read<string>((int)InspectionColumn.Interlayer - 2),
                                    OutsideDiameter = dataRow.Read<string>((int)InspectionColumn.OutsideDiameter - 2),
                                    StressTest = dataRow.Read<string>((int)InspectionColumn.StressTest - 2),
                                    Remark = dataRow.Read<string>((int)InspectionColumn.Remark - 2),
                                    // LotNo = guidString,
                                    Status = OutboundStatus.Normal.GetAttachedString(),
                                };
                                model.CreateDate = model.CreateDate.Markup();
                                list.Add(model);
                            }
                            catch
                            {
                            }
                        }
                    } while (dataRow != null);
                }
            }
            catch (Exception exp)
            {
                udpHeader.Alert("读取上传文件时出错！错误信息：", exp);
                return;
            }

            if (list.Count == 0)
            {
                udpHeader.Alert("在上传的文件里读不到数据，请确保文件的数据正确");
                return;
            }

            int oneHour = 3600;
            ltrMessage.Text = string.Empty;
            var currentIds = list.Select(c => c.ProductID).ToList();
            var existedIds = this.Service.ListExistedProductID(currentIds);
            if (existedIds.Count > 0)
            {
                string ids = string.Join(", ", existedIds.ToArray());
                ltrMessage.Text += string.Format("由于系统已经存在以下产品编号，这些编号被自动排除了：<br/>{0}<br/>", ids);
                list = list.Where(c => !existedIds.Contains(c.ProductID)).ToList();
            }

            var filterList = list.Distinct(new InspectionComparer()).ToList();
            var duplicate = list.Except(filterList);
            if (duplicate.Count() > 0)
            {
                string ids = string.Join(", ", duplicate.Select(c => c.ProductID).ToArray());
                ltrMessage.Text += string.Format("由于以下产品编号重复，这些编号被自动排除了：<br/>{0}<br/>", ids);
                list = filterList;
            }

            Cache.Insert(key, list, oneHour);

            list.ForEach((c, i) => c.Line = i + 1);
            Products.Model = list;
            Products.DataBind();
            Products.SelectAll();

            ltrMessage.Text += Summary(list);
            lnkSave.Enabled = list.Count > 0;

        }

        protected void lnkSave_Click(object sender, EventArgs e)
        {
            string key = getCacheKey();
            var cacheData = Cache[key] as List<Inspection>;
            if (cacheData == null)
            {
                udpHeader.Alert("可能你没有及时上传，数据已经过期，请重新上传Excel文件");
                return;
            }
            List<string> selects = Products.GetSelections();
            if (selects.Count == 0)
            {
                udpHeader.Alert("你没有选择要上传的记录");
                return;
            }
            var uploadList = cacheData.Where(c => selects.Contains(c.ProductID)).ToList();
            this.Service.ImportInspection(uploadList, this.UserName, null);
            udpHeader.Alert("保存成功！");
        }

        private string getCacheKey()
        {
            return CacheKeyBuilder.Join(UserName, RequestUtility.GetIP(), this.GetType().FullName);
        }

        public string Summary(List<Inspection> list)
        {
            string summary = string.Empty;
            var group = list.GroupBy(c => c.CheckDate);
            foreach (var g in group)
            {
                summary += g.Key.ToString(Config.DateFormat);
                summary += string.Format("总检，共{0}条，", g.Count());
                var groupbySpec = g.GroupBy(c => c.ProductSpec).Select(c => "Φ" + c.Key + "×" + c.Count());
                summary += string.Join("，", groupbySpec.ToArray());
                summary += "<br/>";
            }
            return summary;
        }
    }

    public static class Ext
    {
        public static int CountNullOrEmpty(this IEnumerable<object> collection)
        {
            return collection.Where(c => c == null || c.ToString().Trim() == string.Empty).Count();
        }
    }

}
